
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  event;
 
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Vector;


import logger.PoolLogger;

import control.SpecialCharacter;

import sms.SmsBuffer;
import utility.ConvertToLower;
import utility.Input;
import utility.ReplacesSpecialCharacter;
 
import query.query.Query;
 
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;
import file.FileUtility;
 
public class Sendsms implements Event
{
    private boolean Result=true;
    
    GetIdName Gid;
    //SearchRecord sr;
    Vector<Object> RECEIVERnumber = new Vector<Object>();
    String msg;
    String tid;
    int index_vt= -1;
    int index_pv=-1;
    int index_ref=-1;
    Hashtable<Object, Object> table =new Hashtable<Object, Object>();
    String Receiver="receiver";
    String QUERY="query";
    String REPLACER="replacer";
    String MESSAGE="message";
    String MOBILENO="mobileno";
    String Process;

    PoolLogger pl;

    String PROPERTY="^property^";
    String PROPERTYVALUE="^propertyvalue^";
    String userid;
    String request;
    Vector<Object> Condition = new Vector<Object>();
    String datetime;
    
    public Sendsms()
    {
    	// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
    }
    

    public void SetData(String msg, String transaction_type, String tid, String userid)
    {    
    	this.tid =tid;
        RECEIVERnumber.add(userid);
    }
    
    public void initializationData()
    {
        Gid = new GetIdName();
    }
    
    public void setObject(String Object)
    {
        try 
        {
            Hashtable<Object, Object> condition =new Hashtable<Object, Object>();
            RecordSearch rs =new RecordSearch();
            condition.put("td", "null");
            condition.put("mid", Object);
            rs.setConditionMap(condition);
            String result[] = rs.getArrayFromResultSet();
            Hashtable<Object, Object> ConditionMap =new Hashtable<Object, Object>();
            ConditionMap.put("fd",datetime);
            Condition.add(ConditionMap);
            for(int i=0;i<result.length;i++)
            {
                String splitresult[]=result[i].split("\t");
                String value = splitresult[Column.pv_index-1];
                if(value.equals("0"))
                    value =  splitresult[Column.vt_index-1];
                else
                    value = Gid.getItem(value);
                table.put(Gid.getItem(splitresult[Column.pid_index-1]), value);
            }
            table = ConvertToLower.convertHashKey(table);
            condition.put("pid", Gid.getId(QUERY));
            condition.put("td", "null");
            rs.setConditionMap(condition);
            result = rs.getArrayFromResultSet();
            Vector<Object> QueryVector= new Vector<Object>();
            for(int i=0;i<result.length;i++)
            {
                String splitresult[]=result[i].split("\t");
                String value = splitresult[Column.pv_index-1];
                if(value.equals("0"))
                    value =  splitresult[Column.vt_index-1];
                QueryVector.add(value);
            }
            msg = table.get(MESSAGE).toString();
            RECEIVERnumber.addAll(getReceiver(table.get(Receiver).toString()));
            if(!RECEIVERnumber.contains(userid))
            	RECEIVERnumber.add(userid);
            String replacerobject =table.get(REPLACER).toString();
            replacerobject = Gid.getId(replacerobject);
            Hashtable<Object, Object> tempcondition=new Hashtable<Object, Object>();
            tempcondition.put("mid", replacerobject);
            tempcondition.put("td", "null");
            rs.setConditionMap(tempcondition);
            result = rs.getArrayFromResultSet();
            table.clear();
            
            for(int i=0;i<result.length;i++)
            {
                String splitresult[] = result[i].split("\t");
                String value = splitresult[Column.pv_index-1];
                if(value.equals("0"))
                    value =  splitresult[Column.vt_index-1];
                else
                    value = Gid.getItem(value);
                table.put(Gid.getItem(splitresult[Column.pid_index-1]).toLowerCase(), value.toLowerCase());
            }
            for(int k=0;k<QueryVector.size();k++)
            {
                String Query = QueryVector.get(k).toString();
                query.query.Query query = new Query();
                query.initPool();
                query.setObject(Query);
                if(request.equals("master_table") || request.equals("property_details"))
                { 
                    query.setValue(Gid.getItem(tid));
                } 
                else
                { 
                    query.setValue(tid);
                }
                query.settypeofreport("Systemgenerate");
                query.initializeData();
                query.setConditionMap(Condition);
                query.updateReport();
                String buffer[] =query.getbuffer();            
                if(buffer.length>0)
                    {
                        String splitbuffer[] = buffer[0].split("\t");
                        Vector<Object> temp = new Vector<Object>();
                        for(int i=0;i<splitbuffer.length;i++)
                        {
                            temp.add(splitbuffer[i].toLowerCase());
                        }     
                        for(int j=1;j<buffer.length;j++)
                        {
                             Enumeration<Object> enume = table.keys();
                            while(enume.hasMoreElements())
                             { 
                            String property = enume.nextElement().toString().toLowerCase();
                            String replacechar = table.get(property).toString();
                            if(temp.contains(property))
                            {
                                    int index=temp.indexOf(property);
                                    String split[] = buffer[j].split("\t");
                                    if(msg.contains(replacechar))
                                    {
                                        String tempmsg = msg;
                                        int indexofspchar =msg.indexOf(replacechar);
                                        char arr[]=msg.toCharArray();
                                        if(arr[indexofspchar-1]=='+')
                                        {
                                            int tempindex=indexofspchar;
                                            SpecialCharacter sc = new SpecialCharacter();
                                            while(sc.checkSpchar(msg, tempindex))
                                            {
                                                tempindex--;
                                            }   
                                            msg = tempmsg.substring(0,tempindex+1) + " " + split[index] + tempmsg.substring(tempindex+1 ,tempmsg.length());
                                        }   
                                        else
                                        {   
                                        if(j!=buffer.length-1)
                                            msg = tempmsg.substring(0, tempmsg.indexOf(replacechar)) + split[index] + ","+ tempmsg.substring(tempmsg.indexOf(replacechar),tempmsg.length());
                                        else
                                            msg = tempmsg.substring(0, tempmsg.indexOf(replacechar)) + split[index]  + tempmsg.substring( tempmsg.indexOf(replacechar) ,tempmsg.length());
                                        }
                                    }
                                }
                            }
                        }
                    }  
                if(msg.contains(PROPERTY))
                {	
                	if(buffer.length>0)
                	{
                		String splitheading[] = buffer[0].split("\t");
                		for(int j=1;j<buffer.length;j++)
                		{	
                			String splitbuffer[] = buffer[j].split("\t");
	                		for(int i=0;i<splitheading.length;i++)
		                	{
	                			msg = msg.replace(PROPERTY, splitheading[i]);
	                			msg = msg.replace(PROPERTYVALUE, splitbuffer[i]);
	                			msg = msg + "," + PROPERTY +":" +PROPERTYVALUE;
		                	}
                		}
                	}	
                }
            }
            Enumeration<Object> enume = table.keys();
            if(msg.contains(PROPERTY))
            {
            	msg =msg.replace(PROPERTY, "");
            	msg =msg.replace(PROPERTYVALUE, "");
            	int index = msg.lastIndexOf(":");
            	msg = msg.substring(0,index) + msg.substring(index+1, msg.length());
            }
            
            while(enume.hasMoreElements())
            {
                String key = enume.nextElement().toString();
                msg =msg.replace(table.get(key).toString(), "");
            }
            msg= msg.replace("+", "");
            table.put("message", msg);
            
            SmsBuffer smsbuffer =new SmsBuffer();
            for(int i=0;i<RECEIVERnumber.size();i++)
            {
            	smsbuffer.addBufferLog(RECEIVERnumber.get(i).toString(), msg);
            }
            Result =true;
        } catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    
    
    
    public Vector<Object> getReceiver(String reciver)
    {
        Vector<Object> ReceiverList =new Vector<Object>();
         try
        {
            QUERY = Gid.getId(QUERY);
            MOBILENO = Gid.getId(MOBILENO);
            reciver =  Gid.getId(reciver);
            Hashtable<Object, Object> condition = new Hashtable<Object, Object>();
            condition.put("mid", reciver);
            condition.put("td", "null");
            RecordSearch rs =new RecordSearch();
            rs.setConditionMap(condition);
            String line[] = rs.getArrayFromResultSet();
            for(int  i=0;i<line.length;i++)
            {
                String splitline[] = line[i].split("\t");
                String value=splitline[Column.pv_index-1];                
                if(splitline[Column.pid_index-1].equals(MOBILENO))
                {
                   if(value.equals("0"))
                       value =splitline[Column.vt_index-1];
                   else
                       value = Gid.getItem(value);
                   if(!ReceiverList.contains(value.trim()))
                	   ReceiverList.add(value.trim());
                }                
                else if(splitline[Column.pid_index-1].equals(QUERY))
                {    
                    query.query.Query query = new query.query.Query();
                    query.initPool();
                    query.setObject(value);
                    if(request.equals("master_table") || request.equals("property_details"))
                        query.settypeofreport("autoupdate");
                    else
                        query.settypeofreport("Systemgenerate");
                    query.setValue(tid);
                    query.initializeData();
                    query.updateReport();
                    String buffer[] =query.getbuffer();
                    for(int j=1;j<buffer.length;j++)
                    	 if(!ReceiverList.contains(buffer[j].trim()))
                    		 ReceiverList.add(buffer[j].trim());
                }
            }
        }
        catch (Exception e)
        {
            
        }
       return ReceiverList;
    }
 
    public boolean getResult()
    {
        //return Result;
        return true;
    }
 
 

    
    
    public static void main(String[] args)
    {
        Sendsms sms =new Sendsms();
        sms.initializationData();
      //  sms.SetData("", "68", "4", "+919922918602","add");
        sms.setObject("10805");
        System.out.println(sms.msg);
    }

	public boolean afterAdd() 
	{
		return Result;
	}

	public boolean afterDel() 
	{
		return Result;
	}

	public boolean afterMod() 
	{
		return Result;
	}

	public boolean afterView() 
	{
		return Result;
	}
	public boolean SendSms(LinkedList<Object> Mobileno,String msg)
	{
		try 
		{
			SmsBuffer smsbuffer =new SmsBuffer();
			for(int i=0;i<Mobileno.size();i++)
			{
				smsbuffer.addBufferLog(Mobileno.get(i).toString(), msg);
			}
		} catch (Exception e) 
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public void SetData(String Product, String type, String masterid,
			String userid, String Process, String datetime, String request) 
	{   
    	this.tid =masterid;
    	this.userid = userid;
    	this.request =request;
    	this.datetime = datetime;
	}
}